﻿using Farming.Domain;
using Farming.Domain.Input;
using Farming.Repositories;
using Farming.WebApi.Filter;
using IdentityModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Panda.DynamicWebApi;
using Panda.DynamicWebApi.Attributes;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Farming.Service
{
    [DynamicWebApi]
    [ApiExplorerSettings(GroupName = "v1")]
    [Authorize]
    public class AdminService : AdminIService, IDynamicWebApi
    {
        private readonly IRepository<Admin> admin;
        IConfiguration configuration;
        IHttpContextAccessor httpContext;
        public AdminService(IRepository<Admin> admin, IConfiguration configuration, IHttpContextAccessor HttpContext)
        {
            this.admin = admin;
            this.httpContext = HttpContext;
            this.configuration = configuration;
        }
        [HttpGet]
        public async Task<int> DeleteAdmin(int id)
        {
            return await admin.DeleteAsync(id);
        }
        [HttpPost]
        [AllowAnonymous]
        [SkipFilter]
        public async Task<object> Login(LoginInput input)
        {
            var data = await admin.FindAsync(t => t.UserName == input.Username);
            
            if (data == null)
            {
                return new { code = -1, msg = "用户名不存在" };
            }
            else
            {
                data = await admin.FindAsync(t=>t.Password==input.Password);
                if (data == null)
                {
                    return new { code = -1, msg = "密码错误" };
                }
                else
                {
                    var re = admin.GetAllAsync().Result.FirstOrDefault(t => t.UserName == input.Username && t.Password ==input.Password);
                    string token = this.CreateTokenString(re);
                    return new { code = 1, msg = "登陆成功",token=token};
                }

            }
        }
        [HttpGet]
        public async Task<object> GetAdmin()
        {
            var userName = httpContext.HttpContext.User.Identity.Name;
            var http = httpContext.HttpContext.User.FindFirst(JwtClaimTypes.Name)?.Value ;
            var Id= httpContext.HttpContext.User;
            var name = httpContext.HttpContext.User.Claims.FirstOrDefault(t=>t.Type=="name")?.Value;
            var s = httpContext.HttpContext.User.Identities.FirstOrDefault();
            return http;
        }
        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet]
        private string CreateTokenString(Admin admin)
        {
            
            IList<Claim> claims = new List<Claim> {
                        new Claim(JwtClaimTypes.Id,admin.AdminId.ToString()),
                        new Claim(JwtClaimTypes.Name,admin.UserName),
                    };

            //JWT密钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtConfig:Bearer:SecurityKey"]));

            //算法
            var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            //过期时间
            DateTime expires = DateTime.UtcNow.AddHours(10);


            //Payload负载
            var token = new JwtSecurityToken(
                issuer: configuration["JwtConfig:Bearer:Issuer"],
                audience: configuration["JwtConfig:Bearer:Audience"],
                claims: claims,
                notBefore: DateTime.UtcNow,
                expires: expires,
                signingCredentials: cred
                );

            var handler = new JwtSecurityTokenHandler();

            //生成令牌
            string jwt = handler.WriteToken(token);
            return jwt;
        }

    }
}
